<template>
  <view class="container">
    <view class="section">

      <view class="header-image">
        <image src="/static/newimage/123.png?111" mode="aspectFill"
          style="width: 100%;margin: 0 auto;background: #fff;height: 34vw;max-height: 280px;border-radius: 10px;overflow: hidden;">
        </image>
      </view>

      <view class="marquee-container">
        <uni-notice-bar :speed="20" show-icon scrollable :text="gonggao" />
      </view>

      <view class="notice-container">
        注意：下单后因个人原因（不想打了，实名认证失败。对方号码无人接听，号码填错，被对方拉黑等）无法退款，请务必填写真实信息
      </view>

      <view class="con1">
        <!-- <p>自己的号码</p> -->
        <input type="hidden" v-model="formData.my_phone" style="display: none;" />
        <view class="input-group">
          <text>对方的号码</text>
          <input type="number" v-model="formData.you_phone" placeholder="请输入对方的11位号码，不要带+86，不要写自己的手机号！" />
        </view>
        <!-- <template v-if="userInfo.verifyStatus !== 2">
          <view class="input-group">
            <text>你的姓名</text>
            <input type="text" v-model="formData.name" placeholder="请输入你的姓名" />
          </view>

          <view class="input-group">
            <text>你的身份证号码</text>
            <input type="text" v-model="formData.idCard" placeholder="请输入你的身份证号码" />
          </view>
        </template> -->

        <view class="input-group">
          <text>请选择套餐</text>
          <picker mode="selector" :range="packageOptions" range-key="name" @change="onPackageChange">
            <view class="picker">{{ selectedPackage.name || '请选择套餐' }}</view>
          </picker>
        </view>

        <view class="button-group">
          <button class="submit-btn" @click="submitOrderDown">提交拨打</button>
          <button class="contact-btn" @click="contactCustomerService">联系客服</button>
        </view>

        <view class="notes">
          注:1.仅限用于情侣和解通话，禁止拨打营销、骚扰、举报等电话，否则将承担法律责任!
          2.下单后1-20分钟左右出号，不是立即出号，耐心等待即可。
          3.有任何质量问题联系客服
        </view>
      </view>
      <view class="con2">
        <view class="title">
          <image src="/static/image/phone_2.png" alt="" />
          <text>消费记录</text>
        </view>
        <view v-for="(item, index) in orderList" :key="index" class="record-item">
          <view class="record-info">
            <text class="phone-number">订单号：{{ item.orderID }}</text>
            <text class="phone-number">对方号码：{{ item.receiver }}</text>
            <text class="time">创建时间：{{ item.createTime | dateTimeFormat }}</text>
          </view>
          <template v-if="item.payStatus === 1 && item.status === 1">
            <view v-if="!!item.thirdOrderID" class="status makephone" @click="handleCallPhone(item)">
              <text class="status-text">拨打电话</text>
            </view>
            <view v-else class="status">
              <text class="status-text">已支付，处理中</text>
            </view>
          </template>
          <template v-else-if="item.payStatus === 1 && item.status === 4">
            <view class="status">
              <text class="status-text">订单过期</text>
            </view>
          </template>
        </view>
      </view>

    </view>
    <verify-pop ref="refVerifyPop" @onSubmit="submitVerify"></verify-pop>
  </view>
</template>

<script>
  import {
    getNotice,
    getPhoneSetList,
    getUserinfo,
    submitPhoneOrder,
    getTelOrderList,
    payMoney,
    getCallData,
    getMyOrderList,
    submitOrderDown,
    callAuth,
    apiTest1
  } from '@/api/index'
  export default {
    data() {
      return {
        gonggao: '',
        kefu: '',
        formData: {
          my_phone: '',
          you_phone: '',
          name: '',
          idCard: ''
        },
        selectedPackage: {},
        packageOptions: [],
        phoneSetting: {
          price: 100,
          announcement: '欢迎使用匿名通话服务',
        },
        orderList: [],
        showBindPhoneModal: false,
        hdata: {}, // 用户信息数据
        userInfo: {},
        kefu: '',
        timer: null,
        name: '',
        idCard: '',
        thirdOrderID: '',
        sysOrderId: ''
      };
    },
    filters: {
      dateTimeFormat(value) {
        if (!value) return ''
        // 创建一个新的Date对象
        const date = new Date(value * 1000); // 如果timestamp是秒，则需要乘以1000转换为毫秒
        // 获取年、月、日、时、分、秒
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以要加1，并且需要补0
        const day = ('0' + date.getDate()).slice(-2);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);
        // 返回格式化的日期时间字符串
        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
      }
    },
    onLoad() {

      this.$nextTick(() => {
        this.initPage();
      });
      uni.setNavigationBarTitle({
        title: '挽回电话',
      });
    },
    onShow() {
      this.getUserinfo()
      this.getNotice()
      this.getKefu()
      this.getPhoneSetList()
      this.getTelOrderList()

      // webview返回时需要请求这个
      this.callAuth();
    },
    methods: {
      // 获取电话公告
      getNotice() {
        const params = {
          type: 1
        }
        getNotice(params).then(res => {
          const {
            code,
            data
          } = res;
          if (code === 200) {
            this.gonggao = data.content || '';
          }

        })
      },
      getUserinfo() {
        getUserinfo().then(res => {
          // console.log(876, res)
          const {
            code,
            data
          } = res;
          if (code === 200) {
            this.userInfo = data.userInfo;
          }
        })
      },
      getPhoneSetList() {
        getPhoneSetList().then(res => {
          // console.log(111, res)
          const {
            code,
            data
          } = res;
          if (code === 200) {
            this.packageOptions = data.records.map(item => {
              const {
                id,
                name,
                channel,
                price
              } = item
              return {
                name,
                value: id,
                channel,
                price,
                id
              }
            })
          }
        })
      },
      getTelOrderList() {
        const params = {
          page: 1,
          pageSize: 5
        }
        getTelOrderList(params).then(res => {
          const {
            code,
            data
          } = res;
          if (code === 200) {
            console.log(data.records)
            this.orderList = data.records
          }
        })
      },
      initPage() {
        // this.loadOrderList();
        console.log(this.orderList, 'this.orderList');

      },
      loadOrderList() {
        this.packageOptions = [{
            name: '套餐一',
            value: 100
          },
          {
            name: '套餐二',
            value: 200
          }
        ];

        const userInfo = {
          userPhone: ''
        };

        if (!userInfo.userPhone) {
          this.showBindPhoneModal = true;
        } else {
          this.formData.my_phone = userInfo.userPhone;
        }
      },

      onPackageChange(e) {
        // 套餐选择
        const selectedIndex = e.detail.value;
        this.selectedPackage = this.packageOptions[selectedIndex];
        //改价
        this.phoneSetting.price = this.packageOptions[selectedIndex].value
        console.log(this.selectedPackage, 'this.selectedPackage');
      },
      submitOrderDown() {
        // 表单验证
        if (!this.selectedPackage.value) {
          uni.showToast({
            title: '当前没有可用套餐下单，请稍后再试！',
            icon: 'none'
          });
          return;
        }

        if (this.formData.you_phone.length !== 11) {
          uni.showToast({
            title: '请填写11位手机号码。',
            icon: 'none'
          });
          return;
        }

        // if (this.userInfo.verifyStatus !== 2) {
        //   if (!this.formData.name) {
        //     uni.showToast({
        //       title: '请填写你的姓名',
        //       icon: 'none'
        //     });
        //     return;
        //   }
        //   if (!this.formData.idCard) {
        //     uni.showToast({
        //       title: '请填写你的身份号码',
        //       icon: 'none'
        //     });
        //     return;
        //   }
        // }


        if (this.selectedPackage.name === '请选择套餐') {
          uni.showToast({
            title: '请先选择套餐。',
            icon: 'none'
          });
          return;
        }

        const currentSelect = this.packageOptions.find(item => {
          return item.name === this.selectedPackage.name
        })
        const {
          id,
          price
        } = currentSelect;
        console.log(111111, currentSelect)
        const data = {
          channelId: id,
          sender: this.userInfo.username,
          receiver: this.formData.you_phone,
          // name: this.formData.name,
          // idCard: this.formData.idCard
        }
        submitOrderDown(data).then(res => {
          console.log(12345, res)
          const {
            code,
            data
          } = res;
          if (code === 200) {
            console.log(1212, res)
            uni.showModal({
              title: '温馨提示',
              content: `你的订单号为【${data.orderID}】,请截图保存，便于后期查询你的订单`,
              showCancel: true,
              confirmText: "支付宝支付",
              success: (res) => {
                if (res.confirm) {
                  const payParams = {
                    trade_no: data.orderID,
                    money: data.money
                  };
                  payMoney(payParams).then(payRes => {
                    console.log('支付接口返回:', payRes);
                    // 这里可以根据支付接口返回的结果进行处理
                    if (payRes.code === 200) {
                      const url = payRes.data.pay_info
                      uni.navigateTo({
                        url: `/pages/webview/index?title=支付&url=${url}`
                      });
                      // 如果没有实名制，则使用表单中填写的，如果已经实名制了，则需要从userInfo中获取
                      const name = this.formData.name;
                      const idCard = this.formData.idCard
                      if (this.timer != null) {
                        clearInterval(this.timer);
                      }
                      this.timer = setInterval(() => {
                        this.getMyOrderList(data.orderID, name,
                          idCard)
                      }, 2000)
                    }
                  })
                }
              }
            });
          }
        })
      },
      submitOrder() {
        // 表单验证
        if (!this.selectedPackage.value) {
          uni.showToast({
            title: '当前没有可用套餐下单，请稍后再试！',
            icon: 'none'
          });
          return;
        }

        if (this.formData.you_phone.length !== 11) {
          uni.showToast({
            title: '请填写11位手机号码。',
            icon: 'none'
          });
          return;
        }

        if (this.selectedPackage.name === '请选择套餐') {
          uni.showToast({
            title: '请先选择套餐。',
            icon: 'none'
          });
          return;
        }

        const currentSelect = this.packageOptions.find(item => {
          return item.name === this.selectedPackage.name
        })
        const {
          channel,
          price
        } = currentSelect;
        const data = {
          package: channel,
          sender: this.userInfo.username,
          receiver: this.formData.you_phone
        }
        submitPhoneOrder(data).then(res => {
          console.log(43312, res)
          const {
            code,
            data
          } = res;
          if (code === 200) {
            // 调用支付接口
            const payParams = {
              trade_no: data.api_send_id,
              money: price
            };
            payMoney(payParams).then(payRes => {
              console.log('支付接口返回:', payRes);
              // 这里可以根据支付接口返回的结果进行处理
              if (payRes.code === 200) {
                const url = payRes.data.pay_info
                uni.navigateTo({
                  url: `/pages/webview/index?title=支付&url=${url}`
                });
                this.timer = setInterval(() => {
                  this.getMyOrderList(data.api_send_id)
                }, 1000)
              }
            })
          }
        })

        // 提交订单逻辑
        console.log('提交订单', {
          phone: this.formData.my_phone,
          you_phone: this.formData.you_phone,
          package: this.selectedPackage.value,
          userId: this.hdata.userId,
          asdfg: this.hdata.asdfg,
          price: this.phoneSetting.price,
          miniType: this.hdata.miniType,
          openId: this.hdata.openId
        });
      },

      contactCustomerService() {
        uni.showModal({
          title: '客服号码',
          content: this.kefu || '暂无客服信息',
          showCancel: false
        });
      },

      getOrder(orderId) {
        // 获取订单详情
        uni.showModal({
          title: '订单详情',
          content: '订单编号: ' + orderId + '\n请使用本机拨号，按提示操作',
          showCancel: false
        });

        console.log('获取订单详情', orderId);
      },
      closeBindModal() {
        this.showBindPhoneModal = false;
      },
      // 获取电话公告
      getKefu() {
        const params = {
          type: 3
        }
        getNotice(params).then(res => {
          const {
            code,
            data
          } = res;
          // console.log(333333, data)
          if (code === 200) {
            this.kefu = data.content || '';
          }

        })
      },
      getMyOrderList(orderId, name, idCard) {
        const params = {
          orderID: `${orderId}`,
          type: 2
        }
        getMyOrderList(params).then(res => {
          const {
            code,
            data
          } = res;
          if (code === 200) {
            const currentOrder = data.records[0];
            console.log(currentOrder)
            this.name = name;
            this.thirdOrderID = currentOrder.thirdOrderID;
            this.idCard = idCard;
            this.sysOrderId = orderId;
            // 支付成功
            if (currentOrder.payStatus === 1 && currentOrder.status === 1 && currentOrder.thirdOrderID) {
              console.log("支付成功")
              // this.callAuth()
              clearInterval(this.timer)
              this.timer = null;
            }
          }
        })
      },
      callAuth() {
        if (!this.thirdOrderID || !this.name || !this.idCard) return
        const data = {
          sysOrderId: this.sysOrderId,
          sendOrderId: this.thirdOrderID,
          name: this.name,
          idCard: this.idCard
        }
        console.log(data)
        callAuth(data).then(res => {
          console.log(res)
          if (res) {
            // const {
            //   code,
            //   data
            // } = res;
            if (res.data.phoneCallData) {
              const data = res.data.phoneCallData;
              // code === '333'
              uni.showModal({
                title: '号码详情',
                content: `分机号： ${data.fenjihaoma}\n电话号码：${data.bodahaoma}\n下单时间：${data.create_time}\n订单编号：${data.api_send_id}`,
                showCancel: true,
                confirmText: '拨打号码',
                success: (res) => {
                  if (res.confirm) {
                    // 调用系统拨号功能
                    uni.makePhoneCall({
                      phoneNumber: data.bodahaoma, // 电话号码
                      success: () => {
                        console.log('拨号成功');
                      },
                      fail: (err) => {
                        console.log('拨号失败', err);
                        uni.showToast({
                          title: '拨号失败，请重试',
                          icon: 'none'
                        });
                      }
                    });
                  }
                }
              });
            } else if (res.data.authUrl) {
              const url = res.data.authUrl.url;
              uni.navigateTo({
                url: `/pages/webview/index?title=支付&url=${url}`
              });
            }
          }
        })
      },
      getCallData(orderId) {
        const params = {
          sendOrderId: orderId
        }
        getCallData(params).then(res => {
          const {
            code,
            data
          } = res;
          if (code === 200) {

          }
        })
      },
      submitVerify(data) {
        this.name = data.name
        this.idCard = data.idCard;
        this.callAuth();
      },
      //拨打电话
      callPhone(phoneNumber) {
        uni.makePhoneCall({
          phoneNumber: phoneNumber, // 电话号码
          success: () => {
            console.log('拨号成功');
          },
          fail: (err) => {
            console.log('拨号失败', err);
            uni.showToast({
              title: '拨号失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      handleCallPhone(item) {
        this.sysOrderId = item.orderID
        this.thirdOrderID = item.thirdOrderID
        //打电话之前判断用户是否认证
        this.checkUserVerify().then(() => {
          // console.log("已认证")
          this.callPhone(item.receiver)
        }).catch(() => {
          // console.log("未认证")
          this.$refs.refVerifyPop.open()
        });
        // uni.makePhoneCall({
        //   phoneNumber: item.receiver, // 电话号码
        //   success: () => {
        //     console.log('拨号成功');
        //   },
        //   fail: (err) => {
        //     console.log('拨号失败', err);
        //     uni.showToast({
        //       title: '拨号失败，请重试',
        //       icon: 'none'
        //     });
        //   }
        // });
      },
      //判断用户是否认证
      checkUserVerify() {
        return new Promise((resolve, reject) => {
          getUserinfo().then(res => {
            if (res && res.data && res.data.userInfo) {
              let userInfo = res.data.userInfo;
              let verifyStatus = userInfo.verifyStatus
              if ([0, 1].includes(verifyStatus)) {
                reject()
              } else {
                resolve()
              }
            } else {
              reject()
            }
          })
        })
      }
    }
  };
</script>

<style scoped>
  .container {
    background-color: #EFF5FFFF;
    min-height: 100vh;
    padding-bottom: 60rpx;
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 100rpx;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    z-index: 999;
  }

  .footer-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    flex: 1;
  }

  .footer-item image {
    width: 40rpx;
    height: 40rpx;
    margin-bottom: 10rpx;
  }

  .footer-item text {
    font-size: 24rpx;
    color: #666;
  }

  .footer-item.show text {
    color: #007AFF;
  }

  .section {
    padding: 20rpx;
    /* padding-bottom: 10rpx; */
  }

  .header-image {
    /* 	width: 90%; */
    margin: 0 auto;
    background: #fff;
    /* height: 340rpx; */
    /* max-height: 280px; */
    border-radius: 20rpx;
    overflow: hidden;
  }

  .header-image image {
    width: 100%;
    height: 100%;
  }

  .marquee-container {
    margin: 30rpx auto;
    /* background: #fff; */
    border-radius: 20rpx;
    /* padding: 10rpx; */
    /* box-shadow: 0 0 20rpx 0 #e2e2e2; */
    display: block;
    color: #4162ff;
    font-size: 28rpx;
  }

  .notice-container {
    text-align: left;
    width: 94%;
    margin: 30rpx auto;
    background: #fff;
    border-radius: 20rpx;
    padding: 20rpx;
    box-shadow: 0 0 20rpx 0 #e2e2e2;
    display: block;
    color: #060606;
    font-weight: 600;
    font-size: 28rpx;
  }

  .con1,
  .con2 {
    /* width: 94%; */
    margin: 30rpx auto;
    background: #fff;
    border-radius: 20rpx;
    padding: 28rpx;
    box-shadow: 0 0 20rpx 0 #e2e2e2;
  }

  .con1 .input-group {
    margin: 30rpx 0 10rpx 0;
  }

  .con1 .input-group text {
    font-size: 28rpx;
    font-weight: 500;
    display: block;
    margin-bottom: 20rpx;
  }

  .con1 .input-group input,
  .picker {
    width: 100%;
    border: none;
    background: #f4f5f7;
    border-radius: 10rpx;
    height: 80rpx;
    padding: 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }

  .button-group {
    display: flex;
    justify-content: space-between;
    margin-top: 40rpx;
  }

  .submit-btn {
    background: #ebf083;
    border: none;
    border-radius: 10rpx;
    height: 80rpx;
    color: #fff;
    font-size: 32rpx;
    width: 68%;
  }

  .contact-btn {
    background: #ebf083;
    border: none;
    border-radius: 10rpx;
    height: 80rpx;
    color: #fff;
    font-size: 32rpx;
    width: 30%;
    margin-left: 2%;
  }

  .notes {
    margin: 20rpx 0 0 0;
    display: block;
    font-size: 24rpx;
    color: #060606;
    line-height: 1.5;
  }

  .con2 .title {
    font-size: 32rpx;
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .con2 .title image {
    width: 36rpx;
    height: 36rpx;
    margin-right: 10rpx;
  }

  .record-item {
    width: 100%;
    border: none;
    background: #f4f5f7;
    border-radius: 10rpx;
    margin: 20rpx 0;
    padding: 20rpx 0 20rpx 8rpx;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
  }

  .record-info {
    flex: 1;
  }

  .phone-number {
    display: block;
    margin: 0;
    font-size: 28rpx;
  }

  .time {
    font-size: 24rpx;
    color: #7a7a7a;
    margin: 0;
  }

  .status {
    position: absolute;
    color: blue;
    right: 30rpx;
    top: 30rpx;
    font-size: 24rpx;
  }

  .makephone {
    background: blue;
    border-radius: 4px;
    padding: 5px 10px;
    color: #fff;
  }

  .unpaid {
    color: #999;
  }

  .call-btn {
    color: blue;
    cursor: pointer;
  }

  .bind-phone-modal {
    background: rgba(0, 0, 0, 0.7);
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .modal-content {
    width: 80%;
    background: #fff;
    border-radius: 20rpx;
    position: relative;
    padding: 20rpx;
  }

  .close-btn {
    position: absolute;
    right: 20rpx;
    top: 12rpx;
    font-size: 36rpx;
    z-index: 1000;
  }
</style>